import { Ref, useState, useRef, useEffect, useContext } from 'react';
import { Button, Table, message, Form, Row, Col, Input } from 'antd';

import { getProjectTableColumns } from '../mconfig';
import { getProjectService } from '../services';
import '../common/styles.less';

import { SearchOutlined, ReloadOutlined } from '@ant-design/icons';
import { OneModal } from '@/components/one-ui';
import { IOneModalRef } from '@/pages/type';
import { getKeyRouter, onCloseModalCommon } from '@/utils';
import { commonPageSizeOptions, showTotalInfo } from '@/common/constVariable';

const setTableRowClassName = (_: Record<string, any>, index: number) => {
  return index % 2 == 0 ? 'double-row' : 'default-row';
};

/**
 * @UpdateProjectModal 选择项目
 * @param onClose 关闭弹窗组件
 * @param onSave 保存事件
 * @returns
 */
const UpdateProjectModal: React.FC<Record<string, any>> = ({ onClose, onSave }) => {
  const reloadLayoutRef: Ref<IOneModalRef> = useRef(null);

  // 查询条件表单实例
  const [searchForm] = Form.useForm();
  // 表格选中行的key
  const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);
  // 表格选中行内容
  const [selectedRows, setSelectedRows] = useState<Record<string, any>[]>([]);
  // 物料表格数据
  const [dataSource, setDataSource] = useState<Record<string, any>[]>([]);

  // API接口
  const { getProjectRun, getProjectLoading, getProjectPagination } = getProjectService();

  // 获取所有项目列表
  const fetchGetProjectList = async (params: Record<string, any>) => {
    const { rows, msgFlag, msg } = await getProjectRun(params as any);
    if (msgFlag) {
      message.success(msg);

      rows?.forEach((item) => {
        item.projectCode = item?.xmdm; //项目编号
        item.projectName = item?.xmmc; //项目名称
        item.projectSum = item?.ysje; //项目费用（元）
        // item.projectIntro = //项目描述
        item.mockID = getKeyRouter();
      });

      setDataSource(rows);
      return rows;
    } else {
      message.warning(msg);
    }
  };

  // 表格复选框配置
  const rowSelection: any = {
    selectedRowKeys,
    onChange: (selectedRowKeys: React.Key[], selectedRows: Record<string, any>[]) => {
      setSelectedRowKeys(selectedRowKeys);
      setSelectedRows(selectedRows);
    },
    type: 'radio',
  };

  // 保存信息
  const submit = async () => {
    if (!selectedRows.length) {
      message.warning('请勾选内容');
      return;
    }
    onSave(selectedRows[0]);
    onCloseModalCommon(reloadLayoutRef);
  };

  useEffect(() => {
    fetchGetProjectList({});
  }, []);

  // 表格操作按钮
  const modalFooterRender = () => {
    return (
      <>
        <Button
          onClick={() => {
            onCloseModalCommon(reloadLayoutRef);
          }}
        >
          取消
        </Button>
        <Button type={'primary'} onClick={submit}>
          确认
        </Button>
      </>
    );
  };

  /** 表格分页方法改变事件 */
  const handlePaginationChange = (current, pageSize, params) => {
    fetchGetProjectList({ pageSize, current, ...params, ...searchForm.getFieldsValue() });
  };

  return (
    <>
      <OneModal
        open={true}
        getContainer={false}
        ref={reloadLayoutRef}
        title={'预算项目'}
        width={1100}
        onCancel={onClose}
        footer={modalFooterRender()}
        bodyStyle={{
          padding: '5px 10px',
          height: '500px',
          display: 'flex',
          flexDirection: 'column',
        }}
        centered
      >
        <div className={'ProjectModalSearch_contral'}>
          <Form form={searchForm}>
            <Row gutter={[8, 0]}>
              <Col span={4}>
                <Form.Item name={'xmdm'}>
                  <Input placeholder="预算项目编号" />
                </Form.Item>
              </Col>
              <Col span={4}>
                <Form.Item name={'xmmc'}>
                  <Input placeholder="预算项目名称" />
                </Form.Item>
              </Col>
              <Col span={16} style={{ display: 'flex', justifyContent: 'flex-end' }}>
                <Form.Item>
                  <Button
                    type={'default'}
                    icon={<ReloadOutlined />}
                    onClick={() => {
                      searchForm.resetFields();
                      fetchGetProjectList({});
                    }}
                    onMouseOut={(event: any) => {
                      event?.target?.nodeName == 'BUTTON' ? event?.target?.blur() : event.target.parentNode.blur();
                    }}
                    style={{ marginRight: 0, float: 'right' }}
                  >
                    重置
                  </Button>
                  <Button
                    type={'primary'}
                    icon={<SearchOutlined />}
                    onMouseOut={(event: any) => {
                      event?.target?.nodeName == 'BUTTON' ? event?.target?.blur() : event.target.parentNode.blur();
                    }}
                    style={{ marginRight: '8px', float: 'right' }}
                    onClick={() => {
                      fetchGetProjectList({ ...searchForm?.getFieldsValue() });
                    }}
                  >
                    查询
                  </Button>
                </Form.Item>
              </Col>
            </Row>
          </Form>
        </div>
        {/* <div className={`${prefixCls}-material-list list-table listTable-zIndexStyle`}> */}
        <div className={`list-table ProjectModalTable_contral`}>
          <Table
            size="small"
            bordered
            scroll={{ x: 1000, y: 1000 }}
            style={{ margin: '0' }}
            rowClassName={setTableRowClassName}
            loading={getProjectLoading}
            dataSource={dataSource}
            rowSelection={rowSelection}
            columns={getProjectTableColumns()}
            rowKey={'mockID'}
            pagination={
              {
                pageSize: getProjectPagination?.pageSize,
                current: getProjectPagination?.current,
                total: getProjectPagination?.total,
                showQuickJumper: true,
                showSizeChanger: true,
                pageSizeOptions: commonPageSizeOptions,
                showTotal: showTotalInfo,
                onChange: handlePaginationChange,
                // ...getProjectPagination,
                // pageSize: pageSize,
                // current: current,
                // total: total,
                // pageSize: 10,
                // current: 1,
                // total: 11,
              } as any
            }
            onRow={(record) => {
              return {
                onClick: (event) => {
                  setSelectedRowKeys([record?.mockID]);
                  setSelectedRows([record]);
                },
              };
            }}
          />
        </div>

        {/* </div> */}
      </OneModal>
    </>
  );
};

export default UpdateProjectModal;
